package com.gmlive.common.upload.plugin

import com.dingtalk.api.DefaultDingTalkClient
import com.dingtalk.api.DingTalkClient
import com.dingtalk.api.request.OapiRobotSendRequest
import com.taobao.api.ApiException
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.logging.LogLevel
import org.gradle.api.logging.Logger
import org.gradle.util.GradleVersion
//import org.jetbrains.kotlin.gradle.dsl.KotlinProjectExtension
//import org.jetbrains.kotlin.gradle.plugin.getKotlinPluginVersion

class UploadPlugin : Plugin<Project> {
    private var mLogger: Logger? = null
    override fun apply(project: Project) {
        mLogger = project.logger
        //        System.out.println("this is my first buildSrc plugin !");
//        sendMessageToDingTalk();
        log("This is my first buildSrc plugin !!!")
        log("Current Gradle version: " + GradleVersion.current().version)
        log("Kotlin plugin version: " + getKotlinPluginVersion(project))
        project.extensions.create(EXTENSION_NAME, ModuleExtension::class.java)
        project.afterEvaluate { project -> //                ModuleExtension extension = ModuleExtension.getConfig(project);
//
//                project.getExtensions().findByName("android");
//
//                sendMessageToDingTalk(extension);
            project.tasks.create("sendDingTalkMessage", DingTalkTask::class.java)
        }
    }

    private fun sendMessageToDingTalk(extension: ModuleExtension) {
        val client: DingTalkClient = DefaultDingTalkClient(Constants.YINPAO_ROBOT_URL)
        val request = OapiRobotSendRequest()
        request.msgtype = "markdown"
        val markdown = OapiRobotSendRequest.Markdown()
        markdown.title = "SDK助手提示"
        markdown.text = buildMsgText(extension)
        request.setMarkdown(markdown)
        try {
            val response = client.execute(request)
        } catch (e: ApiException) {
            e.printStackTrace()
        }
    }

    private fun buildActionMsgText(): String {
        val sb = StringBuilder()
        sb.append("Someone").append("\n")
        sb.append("------").append("\n")
        sb.append("- 任务: #9").append("\n")
        sb.append("- 执行人：姜志敏").append("\n")
        sb.append("- mapping: ").append("\n")
        return sb.toString()
    }

    private fun buildMsgText(extension: ModuleExtension): String {
        val sb = StringBuilder()
        sb.append("## <font color=#988cfe face=\"黑体\">SDK发布报告</font>")
        sb.append("\n")
        sb.append("### 模块：")
                .append(extension.module)
                .append("\n")
        sb.append("### 版本：")
                .append(extension.version)
                .append("\n")
        sb.append("- 引入方式：\n") //                .append("&emsp;")
                .append("<font color=#008B00 face=\"黑体\">")
                .append("\'")
                .append(extension.groupId).append(":").append(extension.module).append(":").append(extension.version)
                .append("\'")
                .append("</font>")
                .append("\n")
        sb.append("- 使用文档：\n")
        sb.append("###### 发布")
        return sb.toString()
    }

    private fun log(message: String) {
        if (mLogger != null) {
            mLogger!!.log(LogLevel.ERROR, message)
        }
    }

    companion object {
        private const val EXTENSION_NAME = "dingTalkMessage"
        const val ANDROID_EXTENSION_NAME = "android"

//        private fun getKotlinPluginVersion(project: Project): String? {
//            val extension = project.extensions.getByName("kotlin") as KotlinProjectExtension
//            val version = KotlinProjectExtension::coreLibrariesVersion
//
//            return version.get(extension)
//        }

        private fun getKotlinPluginVersion(project: Project): String? {
            val plugin: Plugin<*> = project.plugins.findPlugin("kotlin-android") ?: return null
            return try {
                // No null checks below because we're catching all exceptions.
                val method = plugin.javaClass.getMethod("getKotlinPluginVersion")
                method.isAccessible = true
                method.invoke(plugin).toString()
            } catch (e: Throwable) {
                // Defensively catch all exceptions because we don't want it to crash
                // if kotlin plugin code changes unexpectedly.
                "unknown"
            }
        }
    }
}